﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Shsc.Net.Common.Exeption;
using Shsc.Net.Common.Validator;
using Shsc.Net.Common.Log;
using System.Web.Mvc;

namespace Shsc.Net.Web.Extension
{
    public class ExceptionHandleAttribute : HandleErrorAttribute
    {

        public override void OnException(ExceptionContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
            if (filterContext.IsChildAction)
            {
                return;
            }

            // If custom errors are disabled, we need to let the normal ASP.NET exception handler
            // execute so that the user can see useful debugging information.
            if (filterContext.ExceptionHandled)
            {
                return;
            }

            Exception exception = filterContext.Exception;

            Log4NetLogger.CreateLogger(this.GetType()).Fatal(exception);

            ModelStateDictionary ModelState = filterContext.Controller.ViewData.ModelState;
            if (exception is ValidatorException)
            {
                ValidatorException ex = exception as ValidatorException;
                for (int i = 0; i < ex.ValidatorResultList.Count; i++)
                {
                    if (String.IsNullOrEmpty(ex.ValidatorResultList[i].CtrlId))
                    {
                        ModelState.AddModelError("",
                            ex.ValidatorResultList[i].MessageContent);
                    }
                    else
                    {
                        ModelState.AddModelError(ex.ValidatorResultList[i].CtrlId,
                            ex.ValidatorResultList[i].MessageContent);
                    }
                }
                filterContext.Result = new ViewResult();
                ViewResult result = (ViewResult)filterContext.Result;
                result.ViewData = filterContext.Controller.ViewData;
                //filterContext.Result.ExecuteResult(filterContext);
                filterContext.ExceptionHandled = true;
            }
            else
            {
                base.OnException(filterContext);
            }
        }
    }
}
